﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using VAdvantage.Model;

using VAdvantage.Classes;
using VAdvantage.Grids;
using VAdvantage.Logging;
using VAdvantage.Panels;
using System.Collections;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Controls;
using System.Threading;

namespace VAdvantage.Apps.AForms
{
    public partial class VTrxMaterial : UserControl, FormPanel, IBusy
    {
        #region PrivateVariables
        //Window No			
        private int _windowNo = 0;

        //	FormFrame		
        private FormFrame _frame;

        // MWindow          
        public GridWindow _mWindow = null;
        // MTab pointer     
        public GridTab _mTab = null;

        public Query _staticQuery = null;
        //	Logger			
        private static VLogger log = VLogger.GetVLogger(typeof(VTrxMaterial).FullName);

        public VTextBoxButton vLocatorField = null;
        public VTextBoxButton vProductField = null;
        public VComboBox vcmbOrg = null;
        public VComboBox vcmbMovType = null;

        //GridController          
        public GridController _gridController = null;

        #endregion
        public VTrxMaterial()
        {
            InitializeComponent();
        }
        public void Init(int WindowNo, FormFrame frame)
        {

            _windowNo = WindowNo;
            _frame = frame;
            //_frame.Height = App.Current.Host.Content.ActualHeight - 25;
            //_frame.Width = App.Current.Host.Content.ActualWidth;

            Envs.GetCtx().SetIsSOTrx(_windowNo, true);
            //GetLookUp();
            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            try
            {
                GetLookup();
                JbInit();
                ExecuteQuery();
                // LayOut();

                vdtpFrom.ValueChanged += new EventHandler(vdtpFrom_ValueChanged);
                vdtpTo.ValueChanged += new EventHandler(vdtpTo_ValueChanged);

            }
            catch (Exception ex)
            {
                log.Log(Level.SEVERE, "", ex);
            }
        }

        public void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }

        private void LayOut()
        {
            //vbtnOK.Click += new EventHandler(VOk_Click);
            //vbtnCancel.Click += new EventHandler(VBCancel_Click);
            //vbtnZoom.Click += new EventHandler(VZoom_Click);
            //vbtnRefresh.Click += new EventHandler(VRefresh_Click);
            //vProductField.VetoableChangeListener += new EventHandler(VetoableChange);

            //dtpFrom.cliValueChanged += new EventHandler(VetoableChange);
            //dtpTo.ValueChanged += new EventHandler(VetoableChange);
        }

        /// <summary>
        /// Static Init
        /// </summary>
        private void JbInit()
        {
            vlblOrg.Content = Msg.Translate(Envs.GetContext(), "AD_Org_ID");
            vlblLocator.Content = Msg.Translate(Envs.GetContext(), "M_Locator_ID");
            vlblProduct.Content = Msg.Translate(Envs.GetContext(), "Product");
            vlblDateFrom.Content = Msg.Translate(Envs.GetContext(), "DateFrom");
            vlblDateTo.Content = Msg.Translate(Envs.GetContext(), "DateTo");
            vlblMoment.Content = Msg.Translate(Envs.GetContext(), "MovementType");
        }

        /// <summary>
        /// Initialize Parameter fields
        /// </summary>
        /// 
        public void GetLookup()
        {
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            Context ctx = Envs.GetContext();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                Lookup orgLookup = MLookupFactory.Get(ctx, _windowNo, 3660, DisplayType.TableDir);
                MLocatorLookup locatorLookup = new MLocatorLookup(ctx, _windowNo);
                MLookup productLookup = MLookupFactory.Get(ctx, _windowNo, 3668, DisplayType.Search);
                Lookup mtypeLookup = MLookupFactory.Get(ctx, _windowNo, 3666, DisplayType.List);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => DynParameter(orgLookup, locatorLookup, productLookup, mtypeLookup));
            });
        }
        private void DynParameter(Lookup orgLookup, MLocatorLookup locatorLookup, MLookup productLookup, Lookup mtypeLookup)
        {
            Context ctx = Envs.GetContext();
            //  Organization combo

            //cmbOrg = new Grid.VComboBox("AD_Org_ID", false, false, true, orgLookup, 120);
            vcmbOrg = new VComboBox("AD_Org_ID", false, false, true, orgLookup, 120);
            vcmbOrg.HorizontalAlignment = HorizontalAlignment.Stretch;
            LayoutRoot.Children.Add(vcmbOrg);
            vcmbOrg.Margin = new Thickness(0, 5, 5, 0);
            Grid.SetRow(vcmbOrg, 0);
            Grid.SetColumn(vcmbOrg, 2);
            //  Locator

            vLocatorField = new VTextBoxButton("M_Locator_ID", false, false, true, DisplayType.Locator, locatorLookup, _windowNo);
            vLocatorField.HorizontalAlignment = HorizontalAlignment.Stretch;
            LayoutRoot.Children.Add(this.vLocatorField);
            Grid.SetColumn(vLocatorField, 2);
            Grid.SetRow(vLocatorField, 1);
            vLocatorField.Margin = new Thickness(0, 5, 5, 0);
            //  Product

            vProductField = new VTextBoxButton("M_Product_ID", false, false, true, DisplayType.Search, productLookup);
            vProductField.HorizontalAlignment = HorizontalAlignment.Stretch;
            LayoutRoot.Children.Add(vProductField);
            Grid.SetRow(vProductField, 1);
            Grid.SetColumn(vProductField, 4);
            vProductField.Margin = new Thickness(0, 5, 5, 0);
            //  Movement Type

            //cmbMovType = new VAdvantage.Grids.VComboBox("MovementType", false, false, true, mtypeLookup, 120);
            //vcmbMovType.SetParameter("MovementType", false, false, true, mtypeLookup, 29);
            vcmbMovType = new VComboBox("MovementType", false, false, true, mtypeLookup, 29);
            vcmbMovType.HorizontalAlignment = HorizontalAlignment.Stretch;
            LayoutRoot.Children.Add(vcmbMovType);
            Grid.SetRow(vcmbMovType, 0);
            Grid.SetColumn(vcmbMovType, 4);
            vcmbMovType.Margin = new Thickness(0, 5, 5, 0);
            //  Dates
            vdtpFrom = new SLControls.Controls.VDateTimePicker("DateFrom", false, false, true, SLControls.Controls.DisplayType.Date, Msg.GetMsg(Envs.GetContext(), "DateFrom"));
            vdtpTo = new SLControls.Controls.VDateTimePicker("DateTo", false, false, true, SLControls.Controls.DisplayType.Date, Msg.GetMsg(Envs.GetContext(), "DateTo"));
            //
            vstatusBar.SetStatusLine("");
            SetBusy(false);
        }

        public void ExecuteQuery()
        {

            int AD_Window_ID = 223;
            GridWindowVO wVO = null;
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                wVO= AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);
                _mWindow = new GridWindow(wVO);
                _mTab = _mWindow.GetTab(0);
                _mTab.SetQuery(Query.GetEqualQuery("1", "2"));
                _mTab.Query(0);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => DynInit(_mTab, _mWindow, wVO));
            });
        }

        /// <summary>
        /// Dynamic Layout (Grid).
        /// Based on AD_Window: Material Transactions
        /// </summary>
        private void DynInit(GridTab _mTab, GridWindow _mWindow, GridWindowVO wVO)
        {
            //int AD_Window_ID = 223;	
            //GridWindowVO wVO = AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);


            _staticQuery = new Query();
            _staticQuery.AddRestriction("AD_Client_ID", Query.EQUAL, Envs.GetCtx().GetAD_Client_ID());
            //	Hardcoded

            if (wVO == null)
            {
                SetBusy(false);
                return;
            }
            ////
            _gridController = new GridController(false);
            _gridController.InitGrid(_mTab, true, _windowNo, null, null);
            vdgvRecords.Children.Add(this._gridController);

            vstatusBar.SetStatusLine(" ", false);
            vstatusBar.SetStatusDB(" ");
           // SetBusy(false);
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            _mTab = null;
            if (_mWindow != null)
            {
                _mWindow.Dispose();
            }
            _mWindow = null;

            vcmbOrg = null;
            vLocatorField = null;
            vProductField = null;
            vcmbMovType = null;
            vdtpFrom = null;
            vdtpTo = null;
            //
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
        }

        /// <summary>
        /// change Product event
        /// </summary>
        /// <param name="e"></param>
        public void VetoableChange(object sender, EventArgs e)
        {
            if (((VTextBoxButton)sender).Name.Equals("M_Product_ID"))
            {
                vProductField.SetValue(((VTextBoxButton)sender).Value);
            }
            if (sender is VDateTimePicker)
            {

            }
        }

        int rowSource = 0;

        /// <summary>
        /// Refresh - Create Query and refresh grid
        /// </summary>
        private new void Refresh()
        {

            /**
             *  Create Where Clause
             */
            
            Query query = _staticQuery.DeepCopy();
            //  Organization
            Object value = vcmbOrg.GetValue();
            //no selected value in the Combo
            if (value == null || value.ToString() == "-1" || value.ToString().Trim().Length == 0)
            {
                value = null;
            }
            if (value != null && value.ToString().Length > 0)
            {
                query.AddRestriction("AD_Org_ID", Query.EQUAL, value);
            }
            //  Locator
            value = vLocatorField.GetValue();
            if (value != null && value.ToString().Length > 0)
            {
                query.AddRestriction("M_Locator_ID", Query.EQUAL, value);
            }
            //  Product
            value = vProductField.GetValue();
            if (value != null && value.ToString().Length > 0)
            {
                query.AddRestriction("M_Product_ID", Query.EQUAL, value);
            }
            //  MovementType
            value = vcmbMovType.GetValue();
            if (value == null || value.ToString() == "-1" || value.ToString().Trim().Length == 0)
            {
                value = null;
            }
            if (value != null && value.ToString().Length > 0)
            {
                query.AddRestriction("MovementType", Query.EQUAL, value);
            }
            //  DateFrom
            DateTime? ts = (DateTime?)vdtpFrom.GetValue();
            if (ts != null)
            {
                query.AddRestriction("TRUNC(MovementDate,'DD')", Query.GREATER_EQUAL, ts);
            }
            //  DateTO
            ts = (DateTime?)vdtpTo.GetValue();
            if (ts != null)
            {
                query.AddRestriction("TRUNC(MovementDate,'DD')", Query.LESS_EQUAL, ts);
            }
            log.Info("VTrxMaterial.refresh query=" + query.ToString());

            /**
             *  Refresh/Requery
             */
            this.Cursor = Cursors.Wait;
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            vstatusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "StartSearch"), false);


            _gridController.RegisterIBusy(this);
            _mTab.SetQuery(query);
            //_mTab.Query(0);
            _gridController.query(0, 0, false);
            this.Cursor = Cursors.Arrow;
            vstatusBar.SetStatusLine(" ", false);
            ThreadPool.QueueUserWorkItem(delegate
            {
                Thread.Sleep(1000);
                Dispatcher.BeginInvoke(delegate
                {
                    rowSource = _gridController.RowCount();
                    vstatusBar.SetStatusDB(rowSource);
                    //vstatusBar.SetStatusDB(_gridController.RowCount());
                });
            });

        }

        /// <summary>
        /// Zoom
        /// </summary>
        private void Zoom()
        {
            log.Info("");
            //
            int AD_Window_ID = 0;
            String ColumnName = null;
            String SQL = null;
            //
            int lineID = Envs.GetCtx().GetContextAsInt(_windowNo, "M_InOutLine_ID");
            if (lineID != 0)
            {
                log.Fine("M_InOutLine_ID=" + lineID);
                if (Envs.GetCtx().GetContext(_windowNo, "MovementType").Equals("C-"))
                {
                    AD_Window_ID = 169;     //  Customer Shipment
                }
                else if (Envs.GetCtx().GetContext(_windowNo, "MovementType").Equals("C+"))
                {
                    AD_Window_ID = 409;     //  Customer Return
                }
                else if (Envs.GetCtx().GetContext(_windowNo, "MovementType").Equals("V+"))
                {
                    AD_Window_ID = 184;     //  Vendor Receipt
                }
                else if (Envs.GetCtx().GetContext(_windowNo, "MovementType").Equals("V-"))
                {
                    AD_Window_ID = 411;     //  Vendor Return
                }

                ColumnName = "M_InOut_ID";
                SQL = "SELECT M_InOut_ID FROM M_InOutLine WHERE M_InOutLine_ID=" + lineID;
            }
            else
            {
                lineID = Envs.GetCtx().GetContextAsInt(_windowNo, "M_InventoryLine_ID");
                if (lineID != 0)
                {
                    log.Fine("M_InventoryLine_ID=" + lineID);
                    AD_Window_ID = 168;
                    ColumnName = "M_Inventory_ID";
                    SQL = "SELECT M_Inventory_ID FROM M_InventoryLine WHERE M_InventoryLine_ID=" + lineID;
                }
                else
                {
                    lineID = Envs.GetCtx().GetContextAsInt(_windowNo, "M_MovementLine_ID");
                    if (lineID != 0)
                    {
                        log.Fine("M_MovementLine_ID=" + lineID);
                        AD_Window_ID = 170;
                        ColumnName = "M_Movement_ID";
                        SQL = "SELECT M_Movement_ID FROM M_MovementLine WHERE M_MovementLine_ID=" + lineID;
                    }
                    else
                    {
                        lineID = Envs.GetCtx().GetContextAsInt(_windowNo, "M_ProductionLine_ID");
                        if (lineID != 0)
                        {
                            log.Fine("M_ProductionLine_ID=" + lineID);
                            AD_Window_ID = 191;
                            ColumnName = "M_Production_ID";
                            SQL = "SELECT M_Production_ID FROM M_ProductionLine WHERE M_ProductionLine_ID=" + lineID;
                        }
                        else
                        {
                            log.Fine("Not found WindowNo=" + _windowNo);
                        }
                    }
                }
            }
            if (AD_Window_ID == 0)
            {
                return;
            }

            //  Get Parent ID
            int parentID = 0;
            SetBusy(true);
            txtBusy.Text = Msg.GetMsg("Processing");
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                parentID = Convert.ToInt32(DB.ExecuteScalar(SQL, null, null));
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => ShowWindow(ColumnName, parentID, AD_Window_ID, SQL, lineID));
            });


        }

        public void ShowWindow(String ColumnName, int parentID, int AD_Window_ID, String SQL, int lineID)
        {
            Query query = Query.GetEqualQuery(ColumnName, parentID);
            log.Config("AD_Window_ID=" + AD_Window_ID + " - " + query);
            if (parentID == 0)
            {
                log.Log(Level.SEVERE, "No ParentValue - " + SQL + " - " + lineID);
            }

            //  Zoom
            this.Cursor = Cursors.Wait;

            AWindow frame = new AWindow();
            if (!frame.InitWindow(AD_Window_ID, query))
            {
                SetBusy(false);
                return;
            }
            //AEnv.showCenterScreen(frame);
            // frame.ShowDialog();
            frame.ShowWindow();
            frame = null;
            SetBusy(false);
            //setCursor(Cursor.getDefaultCursor());
        }

        private void vbtnOK_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private void vbtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
           
        }

        private void vbtnZoom_Click(object sender, RoutedEventArgs e)
        {
            Zoom();
        }

        private void vdtpFrom_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                object a = ((SLControls.Controls.VDateTimePicker)sender).Value;
                vdtpFrom.SetValue(a);
            }
            catch { }
        }

        private void vdtpTo_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                object a = ((SLControls.Controls.VDateTimePicker)sender).Value;
                vdtpTo.SetValue(a);
            }
            catch { }
        }

        private void vbtnCancel_Click(object sender, RoutedEventArgs e)
        {
            Dispose();
        }

        private void vdgvRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }


        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }


    }
}

